package org.yray.sip.base;

import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/****
 * 有一种说是这个
 1） HASH1=MD5(username:realm:password)
 2） HASH2=MD5(method:uri)
 3）Response=MD5(HA1:nonce:HA2)
 3502:OfficeTen:Admin111
 13081bdbaa797164c0059889806ba356:23950108:68665b47ae834cdda575637269a9c6ef
 REGISTER:sip:192.168.28.152
 //经验证是第三步以下这种
 3）Response=MD5(HA1:nouce:nc:cnonce:qop:HA2)

 c656dce89150e9d1bd036006b6e0c82f:a9e16e10-f719-48e5-a912-8b87db9adda2:00000001:b273c1e0ab314c799543c8042c93414f:auth:3e678a240d215a31d833afa74148e329
 78002:172.168.200.78:123456
 REGISTER:sip:172.168.200.78:5060
 Digest username="78002", realm="172.168.200.78", nonce="a9e16e10-f719-48e5-a912-8b87db9adda2", uri="sip:172.168.200.78:5060", response="5262febe68d9d82fd9ef16413bb6d71a", algorithm=MD5, cnonce="b273c1e0ab314c799543c8042c93414f", qop=auth, nc=00000001
 */
@Slf4j
public class AuthUtils {

    private AuthUtils(){}
    public static Authorization encryption(Authorization auth,String password)
    {

        Map<String,String> map=auth.getEleMap();
        map.put(Authorization.REALM,map.get(Authorization.REALM));
        map.put(Authorization.URI,map.get(Authorization.URI));
        String haVal1=map.get(Authorization.USERNAME)+":"+map.get(Authorization.REALM)+":"+password;
        String ha1= SecureUtil.md5(haVal1);
        String haVal2="REGISTER:"+map.get(Authorization.URI);
        String ha2=SecureUtil.md5(haVal2);
        String respVal=ha1+":"
                + map.get(Authorization.NONCE)+":"
                + map.get(Authorization.NC)+":"
                + map.get(Authorization.CNONCE)+":"
                + map.get(Authorization.QOP)+":"
                +ha2;
        String resp=SecureUtil.md5(respVal);
        log.info("haVal1={},ha1={},haVal2={},ha2={},respVal={},resp={}",haVal1,ha1,haVal2,ha2,respVal,resp);
        map.put(Authorization.RESPONSE,resp);
        return auth;
    }
}
